import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable()
export class TokenInterceptorService implements HttpInterceptor {

  constructor() {
  }

  // noinspection JSMethodCanBeStatic
  public getToken(): string {
    return localStorage.getItem('token');
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    let auth: string = req.headers.get('auth');
    let request: HttpRequest<any>;
    request = req.clone({headers: req.headers.delete('auth')});
    if (auth !== 'false') {
      auth = 'true';
    }
    if (auth === 'true') {
      request = request.clone({
        headers: req.headers.set('Authorization', `Token ${this.getToken()}`)
      });
    }
    return next.handle(request);
  }
}
